import * as hmUI from "@zos/ui";
import { log as Logger } from "@zos/utils";
const logger = Logger.getLogger("fetch_api");
import { BasePage } from "@zeppos/zml/base-page";
import { getProfile, GENDER_MALE } from '@zos/user'
import { DEVICE_WIDTH, DEVICE_HEIGHT } from "../utils/config/device";
import {
  FETCH_RESULT_TEXT,
} from "zosLoader:./index.[pf].layout.js";
import { createWidget, widget, getTextLayout, event } from '@zos/ui'
import { px } from '@zos/utils'
import { HeartRate, BloodOxygen, Sleep } from '@zos/sensor'
import { create, id, codec } from '@zos/media'
import { mkdirSync } from '@zos/fs'
import { readFileSync } from '@zos/fs'
const result = mkdirSync({
  path: 'voice',
})

if (result === 0) {
  logger.log('创建目录 成功')
} else {
  logger.log('创建目录 失败')

}

// User control
let viewContainer;
let textWidget;

logger.log("=====开始获取传感器数据========");
const { age, gender, height, weight, nickName } = getProfile()
// console.log(age)
const heartRate = new HeartRate()
const bloodOxygen = new BloodOxygen()
const sleep = new Sleep()
const { sleepScore, sleepTotalTime } = sleep.getInfo()
const heartRateValue = heartRate.getLast()
const bloodOxyValue = bloodOxygen.getLastDay()

logger.log("=====开始创建播放器和录音器========");
// console.log(lastValue)
let player = create(id.PLAYER)
let recorder = create(id.RECORDER)

let recordIdx = 0
try {
  player.addEventListener(player.event.PREPARE, function (result) {
    console.log('音频播放：：', result)
    player.start()
    if (result) {
      logger.log('=== prepare succeed ===')
      player.start()
    } else {
      logger.log('=== prepare fail ===')
      player.release()
    }
  })

  player.addEventListener(player.event.COMPLETE, function (result) {
    logger.log('=== play end ===')
    player.stop()
    player.release()
  })
} catch (e) {
  logger.log('开始多媒体失败', e)
}
logger.log("======开始执行程序=======");

Page(
  BasePage({
    state: {},

    onCall({ result }) {
      logger.log('有人调用我了：：：', result)
      if (result && "filePath" in result) {
        logger.log('下载的路径是：：：', result.filePath)
        player.setSource(player.source.FILE, { file: result.filePath })
        player.prepare()
        // this.state.filePath = result.filePath;
        // this.state.isDownload = false;
        // textWidget.setProperty(hmUI.prop.TEXT, getText("transTip"));
      }
    },
    build() {
      let self = this


      viewContainer = createWidget(widget.VIEW_CONTAINER, {
        x: px(0),
        y: px(10),
        w: px(DEVICE_WIDTH),
        h: px(360)
      })
      if (!textWidget) {
        textWidget = viewContainer.createWidget(hmUI.widget.TEXT, {
          ...FETCH_RESULT_TEXT,
          text: '你好，我是小含，是您的心理健康助手！来和我聊聊今天发生的事情吧~'
        });

      } else {
        logger.log('文字框已存在')
        textWidget.setProperty(hmUI.prop.TEXT, '分析中...');
      }

      const recordImg = hmUI.createWidget(hmUI.widget.IMG, {
        src: "assets://audio.png",
        x: (DEVICE_WIDTH - 60) / 2,
        y: px(390),
        w: 60,
        h: 60,
        auto_scale: true
      })
      recordImg.addEventListener(event.CLICK_DOWN, function (info) {
        //控件注册事件监听
        logger.log(info.x)
        recordImg.setProperty(hmUI.prop.MORE, {
          src: "assets://audioPressed.png",
          x: (DEVICE_WIDTH - 60) / 2,
          y: px(390),
          w: 60,
          h: 60,
          auto_scale: true
        })
        recordIdx += 1
        recorder.setFormat(codec.OPUS, {
          target_file: `data://voice/${recordIdx}.opus`
        })
        recorder.start()
        logger.log("录音开始-------------", `data://voice/${recordIdx}.opus`);
      })
      recordImg.addEventListener(event.CLICK_UP, function (info) {
        //控件注册事件监听
        // logger.log(info.x)
        recorder.stop()
        player.setSource(player.source.FILE, { file: `data://voice/${recordIdx}.opus` })
        player.prepare()
        logger.log("播放音乐完成，录音完成，,click button-------", `data://voice/${recordIdx}.opus`);
        // recordImg.setProperty(prop.MORE,{src:"audio.png"})
        recordImg.setProperty(hmUI.prop.MORE, {
          src: "assets://audio.png",
          x: (DEVICE_WIDTH - 60) / 2,
          y: px(390),
          w: 60,
          h: 60,
          auto_scale: true
        })
        if (!textWidget) {
          textWidget = viewContainer.createWidget(hmUI.widget.TEXT, {
            ...FETCH_RESULT_TEXT,
            text: '分析中...'
          });

        } else {
          logger.log('文字框已存在')
          textWidget.setProperty(hmUI.prop.TEXT, '分析中...');
        }
        self.fetchData(recordIdx);

        self.downFile();
      })
    },
    downFile() {
      logger.log('调用DownFile函数了')
      this.request({
        method: "DOWNLOAD_FILE"
      }).then((data) => { }).catch((error) => {
        logger.error("下载error=>%j", error);
      });
    },
    fetchData(audio) {
      let messages = {
        "messages": [{
          "role": "user", "content": `你好，
      我是${nickName || ""}，年龄${age}，身高${height}，体重${weight}，性别是${gender == GENDER_MALE ? '男' : '女'}
      我的心率是：${heartRateValue}，
      我的血氧是：${bloodOxyValue}，
      我昨晚的睡眠时长是：${sleepTotalTime},
      睡眠得分是:${sleepScore}。请简洁明了地和我聊天,聊天内容不要超过80字，不要说客套话，不要用markdown格式，就普通文本即可。`
        }]
      }
      logger.log('调用开始contentBuffer函数了')
      let contentBuffer = readFileSync({
        path: `voice/${recordIdx}.opus`,
      })
      let audioHex=""
      if(contentBuffer){
        audioHex = Buffer.from(contentBuffer).toString('hex')
      }
      // logger.log('11111调用结束contentBuffer函数了')
      // logger.log(arrayBufferToBase64(contentBuffer))
      // logger.log('22222调用结束contentBuffer函数了')
      // console.log('发送前确认：：', JSON.stringify(messages))
      this.request({
        method: "GET_DATA",
        params: { "messages": messages,"audioHex":audioHex}
      })
        .then((data) => {

          const { result = {} } = data;
          logger.log("receive data", result);
          const text = result.data;
          let textStyle = FETCH_RESULT_TEXT
          const { width, height } = getTextLayout(text, {
            text_size: textStyle.text_size,
            text_width: textStyle.w,
            wrapped: 1
          })
          logger.log("width, height ", width, height);
          textStyle.h = height + px(10)
          textStyle.text = text
          if (!textWidget) {
            textWidget = viewContainer.createWidget(hmUI.widget.TEXT, {
              ...FETCH_RESULT_TEXT,
              text,
            });

          } else {
            logger.log('文字框已存在')
            textWidget.setProperty(hmUI.prop.MORE, textStyle);
          }

          player.setSource(player.source.FILE, { file: 'test.mp3' })
          player.prepare()
        })
        .catch((res) => { });
    },
  })
);